var conData = require('MinesConstants');
var logic = require('Logic');
var HexMine = require('HexMine');
var g_gameDataManager = require("g_gameDataManager");
var MessageManager = require("MessageManager");
var prcmd = require("ProtoCmdID")
cc.Class({
    extends: cc.Component,

    properties: {
        minePrefab:
        {
            default:null,
            type:cc.Prefab
        },
        playerPrefab:cc.Prefab,
        playersLis:[require('Player')],
        roles:cc.Node,
        itemLayerNode:cc.Node
    },

    // use this for initialization
    onLoad: function () {
        this.initData();
        this.initView(g_gameDataManager.msgTemp);
    },

    initData:function()
    {
        //this.minesNum =  parseInt(Math.random()*15) + 15;
        //this.boardArray = logic.generBoardData(this.minesNum);

        //var s=[[1,2],[2,3],3,5,6,9];
        //var u= logic.contains(s,[2,3]);
        //console.log('---------->'+u);
        this.minesNum = 0;
        this.haveSelect = false;

        NotificationCenter.on(prcmd.SELECT_GIRD,this.playSelGird,this);
        NotificationCenter.on(prcmd.CALC_SCORE,this.calcScore,this);
        NotificationCenter.on(prcmd.GAME_OVER,this.gameOver,this);
    },


    initView:function(jsonMsg)
    {
        this.minesNum = jsonMsg.data.minesNum;
        this.updateBoard();
        var startPos = cc.p(-304,410);
        var disPos = cc.p(conData.DIS_MINE_COL,conData.DIS_MINE_ROW);
        var boardInfo = jsonMsg.data.boardInfo;
        this.boardArray = [];
        for(var i=0; i<boardInfo.length;i++)
        {
            var lis = boardInfo[i];
            var offsetX = ( i % 2 == 0 ? 0 : 38);
            for(var j=0;j<lis.length;j++)
            {
                var nextPos = cc.pAdd(startPos,cc.p(offsetX+j*disPos.x,-i*disPos.y));
                var mine = cc.instantiate(this.minePrefab);
                mine.setPosition((nextPos));
                this.node.addChild(mine,10-j+i*10,i*10+j);
                var hexMine =  mine.getComponent(HexMine);
                hexMine.setCoord(i,j,lis[j]);

                var eventHandler = new cc.Component.EventHandler();
                eventHandler.target = this.node;
                eventHandler.component = this.__proto__.__classname__ ;
                eventHandler.handler = 'mineTouchCallBack';
                hexMine.clickEvents.push(eventHandler);
            }
            this.boardArray.push(lis);
        }

        var roleLis = jsonMsg.data.rolesInfo;
        for(var i=0;i<roleLis.length;i++)
        {
            var obj = roleLis[i];
            var hasAdd = false;
            this.addPlayer(obj.headUrl,obj.status,obj.score,obj.usrID);
        }
    },

    addPlayer:function(headUrl,status,score,usrID)
    {
        var player = cc.instantiate(this.playerPrefab);
        var rolesCount = this.playersLis.length;
        var pos = this.getPlayerPos(rolesCount);
        player.setPosition(pos);
        this.roles.addChild(player);
        var playerCon = player.getComponent(require('Player'));
        var str = "正在选择";
        if(status == 1)
        {
            str = "已经选好";
        }
        playerCon.setStateLabel(str);
        playerCon.setScoreLabel(score);
        playerCon.setUsrID(usrID);
        playerCon.loadHeadUrl(headUrl);
        this.playersLis.push(playerCon);
    },


    getPlayerPos:function(index)
    {
        var offsetPos = cc.p(-287,-317);
        var disX = 117;
        var addPos = cc.p(index*disX,0);
        var pos = cc.pAdd(offsetPos,addPos);
        return pos;
    },


    mineTouchCallBack:function(event)
    {
        if(this.haveSelect)
        {
            console.log("已经选择过了 不能再选");
            return;
        }

        var hexMine = event.target.getComponent(HexMine);
        if(this.isOpened(hexMine.row,hexMine.col))
        {
            console.log("已经翻开的 不能再选");
            return;
        }

        this.haveSelect = true;
        var curSec = new Date().getTime();
        var isMarkMine = false;
        if(curSec - hexMine.touchBeganTime_msec > 300)
        {
            isMarkMine = true;
        }

        var msg = {
            'cmdID': prcmd.SELECT_GIRD,
            'data': {
                'row':hexMine.row,
                'col':hexMine.col,
                'isMarkMine':isMarkMine
            }
        };
        MessageManager.sendMessage(JSON.stringify(msg));
    },

    isOpened:function(row,col)
    {
        var num = this.boardArray[row][col];
        return num != prcmd.GIRD_NOT_OPENED;
    },

    playSelGird:function(eventObj)
    {
        console.log("playSelGird");
        var data = eventObj.msg.data;
        var selPlayerInfo = data.selPlayerInfo;
        var selUsrId = selPlayerInfo.usrID;
        var selPlayer = null;
        for(var i=0 ; i<this.playersLis.length;i++)
        {
            var player = this.playersLis[i];
            if(player.getUsrID() == selUsrId)
            {
                player.setStateLabel("已经选好");
                selPlayer = player;
                break;
            }
        }
        var selInfo = selPlayerInfo.selInfo;
        var row = selInfo.row;
        var col = selInfo.col;
        var isMarkMine = selInfo.isMarkMine;
        var hexMineNode = this.node.getChildByTag(row*10+col);
        if(hexMineNode)
        {
            var hexMine = hexMineNode.getComponent(HexMine);
            hexMine.addSelPlayer(player.head.spriteFrame,isMarkMine,selUsrId);
        }
    },

    calcScore:function(eventObj)
    {
        console.log("calcScore");
        var data = eventObj.msg.data;
        this.minesNum = data.minesNum;
        this.updateBoard();
        var boardInfo = data.boardInfo;
        for(var i=0; i<this.boardArray.length;i++)
        {
            var lis = this.boardArray[i];
            for(var j=0;j<lis.length;j++)
            {
                var girdNode = this.node.getChildByTag(i*10+j);
                var mineCon = girdNode.getComponent(HexMine);
                var girdNum = boardInfo[i][j];
                if(girdNum != prcmd.GIRD_NOT_OPENED)
                {
                    //console.log("hide"+i+" "+j+ " "+girdNum);
                    mineCon.state = girdNum;
                    mineCon.open();
                }
            }
        }

        var rolesInfo = data.rolesInfo;
        for(var i=0;i<rolesInfo.length;i++)
        {
            var obj = rolesInfo[i];
            var selInfo = obj.selInfo;
            var selRow = selInfo.row;
            var isMarkMine = selInfo.isMarkMine;
            var selCol = selInfo.col;
            var usrID = obj.usrID;
            var deductCoin = obj.deductCoin;
            var addScore = obj.addScore;
            var score = obj.score;
            var girdNode = this.node.getChildByTag(selRow*10+selCol);
            var mineCon = girdNode.getComponent(HexMine);
            mineCon.calcScore(usrID,addScore,deductCoin,isMarkMine);
            for(var j=0; j< this.playersLis.length;j++)
            {
                var player = this.playersLis[j];
                if(player.getUsrID() == usrID)
                {
                    player.setScoreLabel(score);
                    player.setStateLabel("正在选择");
                    break;
                }
            }
        }

        this.haveSelect = false;
    },


    gameOver:function(eventObj)
    {
        g_gameDataManager.msgTemp = eventObj.msg;
        cc.director.loadScene('GameOver');
    },

    updateBoard:function()
    {
        this.itemLayerNode.getComponent(require('ItemLayer')).updateMinesNum();
    },

    onDestroy:function()
    {
        NotificationCenter.off(prcmd.SELECT_GIRD,this.playSelGird);
        NotificationCenter.off(prcmd.CALC_SCORE,this.calcScore);
        NotificationCenter.off(prcmd.GAME_OVER,this.gameOver);
    }

});
